#========#
# Plot 1 #
#========#

rm(list = ls())


# Load necessary libraries
library(ggplot2)
library(dplyr)
library(readxl)


# Read the data from the first sheet of the Excel file
dta_plot <- read_excel("/Users/Enrijeta/Dropbox/Hood et al. Registered Indies/SPPQ/SPPQ_replication/plot/plot1.xlsx")


# Assuming your data is already loaded into a dataframe called dta_plot
# Adjust the group column as a factor if it's not already
dta_plot$group <- as.factor(dta_plot$group)


# Create the plot
ggplot(dta_plot, aes(x = group, y = margin)) +   
  geom_point(size = 3, color = "black") +  # Plot the points   
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) +  # Add error bars for CIs   
  facet_wrap(~ state) +  # Create separate panels by state
  labs(title = "", x = "PID Strength", y = "Probability NPA/Unaffilated Registrant") +   
  scale_x_discrete(labels = c("1" = "Pure Independent", 
                              "2" = "Independent Leaner", 
                              "3" = "Weak Partisan", 
                              "4" = "Strong Partisan")) +  # Label the x-axis ticks
  scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = 0.1)) +  # Set y-axis from 0 to 1 with 0.10 intervals
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 9.5),  # Rotate x-axis labels
        strip.background = element_rect(fill = "lightgray", color = "black", size = 0.5),  # Rectangle for facet labels
        strip.text = element_text(face = "bold", size = 10),  # Custom font for facet text
        panel.grid.major = element_line(size = 0.3),  # Make major grid lines thinner
        panel.grid.minor = element_line(size = 0.2))  # Make minor grid lines thinner




